using System;
using System.Collections;

namespace Caramel
{
	public class ThreadLocalStorage : ILocalStorage
	{
		[ThreadStatic()]
		private static Hashtable Hashtable;

		public object this[object key]
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return null;
				}
				
				return ThreadLocalStorage.Hashtable[key];
			}
			set
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					ThreadLocalStorage.Hashtable = new Hashtable();
				}

				ThreadLocalStorage.Hashtable[key] = value;
			}
		}

		public void Clear()
		{
			if (ThreadLocalStorage.Hashtable == null)
			{
				return;
			}

			ThreadLocalStorage.Hashtable.Clear();
		}

		public void Add(object key, object value)
		{
			ThreadLocalStorage.Hashtable.Add(key, value);
		}

		public bool Contains(object key)
		{
			if (ThreadLocalStorage.Hashtable == null)
			{
				return false;
			}

			return ThreadLocalStorage.Hashtable.Contains(key);
		}

		public IDictionaryEnumerator GetEnumerator()
		{
			if (ThreadLocalStorage.Hashtable == null)
			{
				return null;
			}

			return ThreadLocalStorage.Hashtable.GetEnumerator();
		}

		public bool IsFixedSize
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return false;
				}

				return ThreadLocalStorage.Hashtable.IsFixedSize;
			}
		}

		public bool IsReadOnly
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return false;
				}

				return ThreadLocalStorage.Hashtable.IsReadOnly;
			}
		}

		public ICollection Keys
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return null;
				}

				return ThreadLocalStorage.Hashtable.Keys;
			}
		}

		public void Remove(object key)
		{
			if (ThreadLocalStorage.Hashtable == null)
			{
				return;
			}

			ThreadLocalStorage.Hashtable.Remove(key);
		}

		public ICollection Values
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return null;
				}

				return ThreadLocalStorage.Hashtable.Values;
			}
		}

		public void CopyTo(Array array, int index)
		{
			if (ThreadLocalStorage.Hashtable == null)
			{
				return;
			}

			ThreadLocalStorage.Hashtable.CopyTo(array, index);
		}

		public int Count
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return 0;
				}

				return ThreadLocalStorage.Hashtable.Count;
			}
		}

		public bool IsSynchronized
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return false;
				}

				return ThreadLocalStorage.Hashtable.IsSynchronized;
			}
		}

		public object SyncRoot
		{
			get
			{
				if (ThreadLocalStorage.Hashtable == null)
				{
					return null;
				}

				return ThreadLocalStorage.Hashtable.SyncRoot;
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}
	}
}
